<template>
<div class="order-wrap">
    <G_header title="全部订单" />
    <van-tabs v-model="active" @change="getData">
        <van-tab :title="item" v-for="item in topNavText" :key="item">
            <div style="padding: .25rem 7px">
                <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
                    <order :data="orderItem"  @getChangestatus="getChangestatus" @getStore="getStore" @getdetail="getdetail" @getPayOrder="getPayOrder" />
                </van-list>
                <Copyright />
            </div>
        </van-tab>
    </van-tabs>
    <van-popup v-model="show" :style="{ height:'40%' }" position="bottom">
        <van-cell-group title="选择支付方式">
            <van-cell title="微信支付" is-link @click="pay('1')" />
            <van-cell title="余额支付" is-link @click="pay('2')" />
        </van-cell-group>
    </van-popup>
</div>
</template>

<script>
import order from "@/components/orderItem";
import Copyright from "@/components/copyright";
import pay from "@/views/utils/pay";
import {
    Dialog
} from 'vant';
import {
    Notify
} from 'vant';
import wx from 'weixin-js-sdk'
export default {
    name: "Order",
    data() {
        return {
            topNavText: ['全部', '待付款', '待发货', '配送中', '待收货', '待评价', '待退款'],
            dataList: null,
            active: 0,
            orderUrl: '',
            loading: true,
            finished: false,
            page: 1,
            lastPage: null,
            currentPage: 1,
            maxPage: null,
            show: false,
            current_order_id: null,
            orderItems: [],
            orderItem: []
        }
    },
    components: {
        order,
        Copyright
    },
    created() {
        this.token = sessionStorage.getItem("token");
        this.active = this.$route.params.index;
        this.userInfo = this.global.state.userInfo;
        this.getData();
    },
    watch: {

    },
    methods: {
        getData() {
            let type;
            switch (this.active) {
                case 1:
                    type = 'Wait';
                    break;

                case 2:
                    type = 'Paid';
                    break;

                case 3:
                    type = 'Dispatch';
                    break;

                case 4:
                    type = 'Unpaid';
                    break;

                case 5:
                    type = 'Finish';
                    break;

                case 6:
                    type = 'Refund';
                    break;

                default:
                    type = '';
                    break;
            }
            this.type = type;
            this.lastPage = null;
            this.currentPage = null;
            this.maxPage = null;
            this.finished = false;
            this.getDataList();
        },
        onLoad() {
            this.getDataList();
        },
        currentTabs() {

        },
        getDataList() {
            let url = '/api/store/user/order/list/' + this.type;
            let params = {};
            params.token = this.token;
            params.user_id = this.userInfo.id;
            params.page = this.currentPage;
            if (this.maxPage == null || this.currentPage <= this.maxPage) {
                this.axios.get(url, {
                    params
                }).then(result => {
                    this.maxPage = result.data.data.last_page;
                    this.currentPage = result.data.data.current_page + 1;
                    let data = [];
                    result.data.data.data.forEach(item => {
                        item.params = JSON.parse(item.params);
                        if(item.dispatch_info){
                            item.dispatch_info = JSON.parse(item.dispatch_info);
                        }else {
                            let info = {};
                            info.str = 'xd0_123';
                            info.num= 'xd0_123';
                            item.dispatch_info = info
                        }
                    });
                    if (result.data.data.current_page == 1) {
                        this.orderItem = result.data.data.data;
                    } else {
                        let newData = [...this.orderItem, ...result.data.data.data]
                        this.orderItem = newData;
                        console.log(this.orderItem)
                    }
                    this.loading = false;
                }).catch(err => {
                    console.log(err)
                })
            } else {
                this.loading = false;
                this.finished = true;
            }
        },
        getdetail(item) {
            this.global.state.orderDetailsData = item;
            this.$router.push({
                path: './order/detail'
            })
        },
        getChangestatus(e) {
            let url = '/api/store/user/order/status/' + e.id;
            let params = {};
            params.token = this.token;
            params.status = 'Finish';
            Dialog.confirm({
                title: '提示',
                message: '您确认要完成订单吗?'
            }).then(() => {
                this.axios.get(url, {
                    params
                }).then(res => {
                    Notify({
                        type: 'success',
                        background: '#07c160',
                        message: res.data.message
                    });
                    this.getData();
                }).catch(err => {
                    console.log(err)
                })
            }).catch(() => {
                // on cancel
            });

        },
        getStore(store) {
            // 店家
            this.global.state.productMerchant_store = store;
            this.$router.push({
                path: '../store/'
            })
        },
        getPayOrder(item) {
            this.show = true;
            this.current_order_id = item.id;
        },
  
        pay(e) {
            let params = {};
            params.token = sessionStorage.getItem("token");
            switch (e) {
                case '1':
                    params.pay_mode = 'wechat';
                    break;

                default:
                    params.pay_mode = ' ';
                    break;
            }

            this.axios.post('api/store/user/order/pay/' + this.current_order_id, params).then(res => {
                if (res.data.code == 200) {
                    if (e == 1) {
                        pay.wxpay(res.data.data);
                    } else {
                        this.show = false;
                        Notify({
                            type: 'success',
                            background: '#07c160',
                            message: res.data.message
                        });
                        this.getData();
                    }

                }
            }).catch(err => {
                console.log(err)
            })
        },
        wxPay(data) {
            let params = {};
            params.token = sessionStorage.getItem("token");
            this.axios.get('/api/wechatofficial/1/share_config/', {
                params
            }).then(res => {
                let configData = res.data.data;
                // debugger;
                wx.config({
                    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId: configData.appId, // 必填，公众号的唯一标识
                    timestamp: configData.timestamp, // 必填，生成签名的时间戳
                    nonceStr: configData.nonceStr, // 必填，生成签名的随机串
                    signature: configData.signature, // 必填，签名，见附录1
                    jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                });
                wx.ready(function () {
                    wx.chooseWXPay({
                        timestamp: data.timestamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                        nonceStr: data.nonceStr, // 支付签名随机串，不长于 32 位
                        package: data.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
                        signType: data.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                        paySign: data.paySign, // 支付签名
                        success: function (res) {
                            Dialog({
                                message: res
                            });
                            this.getData();
                        },
                        fail: function (res) {
                            Dialog({
                                message: res
                            });
                            errorCb(res);

                        }
                    });
                });
                wx.error(function (res) {
                    Dialog({
                        message: res
                    });
                    alert(res)
                    console.log('err', res)
                });
            }).catch(err => {
                console.log(err)
            })
        }
    }
};
</script>
